﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Senparc.Weixin.MP.AdvancedAPIs.OAuth;
using Senparc.Weixin.MP.AdvancedAPIs;
using chihuopig.IService;
using System.Net.Http;
using Newtonsoft.Json;
using chihuopig.DTO;
using chihuopig.Model;

namespace chihuopig.Web.Web.Controllers
{
    public class WeChatAppLoginController : Controller
    {
        ImemberService _imemberService;
        public WeChatAppLoginController
        (
            ImemberService imemberService
        )
        {
            _imemberService = imemberService;
        }
        public IActionResult Index()
        {
            return View();
        }
        public override async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            HttpClient client = new HttpClient();
            string code = Request.Query["code"];
            ChatAppUserInfo userInfo= JsonConvert.DeserializeObject<ChatAppUserInfo>(Request.Query["Userinfo"]);
            HttpResponseMessage mes=  await client.GetAsync($"https://api.weixin.qq.com/sns/jscode2session?appid=wx8435cbc8e761cead&secret=2fbec9c6de8e7934eb14aa07671e5b64&js_code={code}&grant_type=authorization_code");
            if (mes.StatusCode== System.Net.HttpStatusCode.OK)
            {
                WeChatAppLoginDTO WeChatAppLogin = JsonConvert.DeserializeObject<WeChatAppLoginDTO>(await mes.Content.ReadAsStringAsync());
                Member member=chihuopig.Service.DBService.Sqlclient.Queryable<Member>().Where(s => s.openId == WeChatAppLogin.openid).Single();
                if(member==null)
                {
                   long id= chihuopig.Service.DBService.Sqlclient.Insertable<Member>(new Member()
                    {
                         Addtime=DateTime.Now,
                         city= userInfo.city,
                         headimgurl= userInfo.avatarUrl,
                         money=0.00m,
                         nickname= userInfo.nickName,
                         openId= WeChatAppLogin.openid,
                         Sex=Convert.ToInt32(userInfo.gender),
                         unionid= WeChatAppLogin.unionid

                    }).ExecuteReturnBigIdentity();


                }
                context.Result = new JsonResult(WeChatAppLogin);
                return;
            }

            context.Result = new ContentResult() { Content="{\"IsLoginok\":\"false\"}", StatusCode=500, ContentType= "application/json" };
        }
    }
}